MOBILE = {};

MOBILE.Init = function() {
	MOBILE.DetectBuggyDevices();
}

MOBILE.DetectBuggyDevices = function() {
	MOBILE.IsBuggyAndroid = false;
	MOBILE.IsBuggyIOS = false;
	var ua = navigator.userAgent;
	if( ua.indexOf("Android") >= 0 ){
		var androidversion = parseFloat(ua.slice(ua.indexOf("Android")+8));
		if(androidversion < 4){
			MOBILE.IsBuggyAndroid = true;
		}
	}else if(/iP(hone|od|ad)/.test(ua)) {
		var regex = ua.match(/OS (\d+)_(\d+)_?(\d+)?/);
		var iOSVersion = parseInt(regex[1], 10);
		if(iOSVersion<6){
			MOBILE.IsBuggyIOS = true;
		}
	}
}

MOBILE.BindNoClickDelay = function(jquerySelection) {
	if(window.isTouch) {
		$.each(jquerySelection, function(index, element) {
			new MOBILE.NoClickDelay(element);
		});
	}
}

MOBILE.NoClickDelay = function(el) {
	this.element = el;
	this.element.removeEventListener('touchstart', this, false);
	this.element.addEventListener('touchstart', this, false);
};

MOBILE.NoClickDelay.prototype = {
	handleEvent: function(e) {
		switch(e.type) {
			case 'touchstart': this.onTouchStart(e); break;
			case 'touchmove': this.onTouchMove(e); break;
			case 'touchend': this.onTouchEnd(e); break;
		}
	},

	onTouchStart: function(e) {
		this.moved = false;
		this.element.removeEventListener('touchmove', this, false);
		this.element.removeEventListener('touchend', this, false);
		this.element.addEventListener('touchmove', this, false);
		this.element.addEventListener('touchend', this, false);
	},

	onTouchMove: function(e) {
		this.moved = true;
	},

	onTouchEnd: function(e) {
		e.preventDefault();
		this.element.removeEventListener('touchmove', this, false);
		this.element.removeEventListener('touchend', this, false);

		if( !this.moved ) {
			var theTarget = document.elementFromPoint(e.changedTouches[0].clientX, e.changedTouches[0].clientY);
			if(theTarget.nodeType == 3) theTarget = theTarget.parentNode;

			var theEvent = document.createEvent('MouseEvents');
			theEvent.initEvent('customClick', true, true);
			theTarget.dispatchEvent(theEvent);

//			$(this).trigger('customClick');

		}
	}
};

$(document).ready(function() {
	MOBILE.Init();
});